﻿#region << 文 件 说 明 >>

/*----------------------------------------------------------------
// 文件名称：ViewModelLocator
// 创 建 者：杨程
// 创建时间：2021/10/19 10:18:15
// 文件版本：V1.0.0
// ===============================================================
// 功能描述：
//
//
//----------------------------------------------------------------*/

#endregion

using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using System;
using System.Net.Sockets;
using System.Net;
using System.Text;
using test.Model;
using Vampirewal.Core.Components;
using Vampirewal.Core.ComputerInfo;
using Vampirewal.Core.EventBus;
using Vampirewal.Core.Extensions;
using Vampirewal.Core.Interface;
using Vampirewal.Core.Models;
using Vampirewal.Core.OperationExcelService;
using System.Threading.Tasks;
using Vampirewal.Core.RuleEngine;
using System.Collections.Generic;
using Vampirewal.Core.FlowEngine;
using Vampirewal.Core;
using Vampirewal.Core.Models.FlowEngine;
using Vampirewal.Core.MiniApi;
using Microsoft.AspNetCore.Builder;
using Microsoft.OpenApi.Models;
using System.IO;
using Microsoft.AspNetCore.Routing;
using System.ComponentModel;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using System.Reflection;
using NPOI.OpenXmlFormats.Spreadsheet;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata;
using Vampirewal.Core.WebApi;
using Vampirewal.Core.ConfigOptions;
using TouchSocket.Sockets;
using TouchSocket.Core;
using TouchSocket.Dmtp;
using Microsoft.Extensions.FileProviders;
using Vampirewal.Core.ScheduledTask;
using System.Threading;
using Vampirewal.Core.SimpleMVVM;
using System.Diagnostics;

//using Vampirewal.Core.VContainer;

namespace test.ViewModel;

public class TestBootStartUp : VampirewalBootStartUp
{
    protected override string FirstViewKey => "MainView";

    protected override void GetStartArgs(string[] args)
    {

    }

    //public override void Configure(IApplicationBuilder app)
    //{
    //    //启用静态文件
    //    app.UseStaticFiles();

    //    //使用文件目录，类似FTP
    //    app.UseDirectoryBrowser(new DirectoryBrowserOptions()
    //    {
    //        FileProvider=new PhysicalFileProvider($"{AppDomain.CurrentDomain.BaseDirectory}Files"),
    //        RequestPath="/Upload"
    //    });

    //    //启用内置全局异常捕获中间件
    //    app.UseVampirewalMiniApiExceptionHandler();

    //    app.UseSwagger();
    //    app.UseSwaggerUI(c =>
    //    {
    //        c.SwaggerEndpoint("/swagger/v1/swagger.json", "MiniApi");

    //        c.EnablePersistAuthorization();
    //    });

    //    app.UseVampirewalCoreScheduledTask();
    //}


    //public override void SetEndpointRouteBuilder(IEndpointRouteBuilder endpoint)
    //{
    //    endpoint.MapGet("/GetName/{name}/{age}", (string name, int age) =>
    //    {
    //        return $"{name}:傻屌,今年{age}岁";
    //    }).WithTags("shadiao").WithName("傻屌");
    //}



    protected override void RegisterService(IServiceCollection services)
    {
        //WorkParameterCompare com = new WorkParameterCompare()
        //{
        //    AssemblyName = "haha",
        //    ParamValues = new Vampirewal.Core.Models.FlowEngine.WorkParamCollection()
        //    {
        //        new Vampirewal.Core.Models.FlowEngine.WorkParam() { ParamName = "ceshi", ParamValue = "121" },
        //        new Vampirewal.Core.Models.FlowEngine.WorkParam() { ParamName = "name", ParamValue = "haha" },
        //    },
        //    ParamTemplates = new List<Vampirewal.Core.Models.FlowEngine.FlowParam>()
        //    {
        //        new Vampirewal.Core.Models.FlowEngine.FlowParam() { ParameterName = "ceshi", ValueType = Vampirewal.Core.Models.FlowEngine.ParameterValueType.Decimal },
        //        new Vampirewal.Core.Models.FlowEngine.FlowParam() { ParameterName = "name", ValueType = Vampirewal.Core.Models.FlowEngine.ParameterValueType.String },
        //    },
        //    Condition = "work.ceshi>120 and 'work.name'<>'haha1'"
        //};

        //com.Compare();


        //services.AddVampirewalCoreConfig($"{AppDomain.CurrentDomain.BaseDirectory}AppConfig.json");
        //services.AddVampirewalCoreConfig($"{AppDomain.CurrentDomain.BaseDirectory}AppConfig.json", options =>
        //{
        //    //options.RegisterOptions<AppBaseOptions>();
        //    options.RegisterOptions<DbBaseOptions>();
        //    options.RegisterOptions<VampirewalMiniApiOptions>();
        //});

        services.AddVampirewalCoreAppConfig(config =>
        {
            config.LoadOption<DbBaseOptions>();
            config.LoadOption<VampirewalMiniApiOptions>();
            config.LoadOption<TestConfig>();
        });

        


        //services.AddSingleton<IAppConfig, VampirewalConfig>();
        services.AddSingleton<IVampirewalCoreDataContext, DataContext>();
        //services.UseVampirewalCoreSqlSugar(new testdc());
        services.UseVampirewalCoreSqlSugar<testdc>();
        services.AddTransient(typeof(SqlSugarRepository<>));
        services.AddSingleton<IVampirewalCoreLogService, VampirewalCoreLogService>();
        services.AddVampirewalCoreDialogMessage();
        services.AddVampirewalCoreMdiService();
        services.AddSingleton<IVampirewalOperationExcelService, VampirewalOperationExcelService>();
        services.AddSingleton<IVampirewalCoreComputerService, VampirewalCoreComputerService>();
        services.AddSingleton<IVampirewalCoreActionService, VampirewalCoreActionService>();
        services.AddSingleton<IVampirewalCoreValidationService, VampirewalCoreValidationService>();

        //services.AddVampirewalCoreEventFactory();
        services.AddVampirewalCoreEventBusFactory();
        services.AddVampirewalCoreEventAggregatorService();


        //services.AddVampirewalControllers().AddVampirewalApiResultProvider<VampirewalApiResultProvider>();

        //services.UseVampirewalWebApi(config =>
        //{
        //    config.SetIpPort("*", 9999);

        //    config.AddVampirewalMiddleware<GlobalExceptionMiddleware>();
        //    config.AddVampirewalMiddleware<TestMiddleware>();

        //    config.UseWebApiDoc(new VampirewalApiDocOptions()
        //    {
        //        LocalPath = AppDomain.CurrentDomain.BaseDirectory,
        //        Title = "测试",
        //        Version = "1.0.0.1"
        //    });
        //});

        //services.AddVampirewalRuleEngine(option =>
        //{
        //    option.RegisterRule<TestRule, TestModel>("haha");
        //});

        //services.AddVampirewalWorkFlowEngineServer<VampirewalWorkFlowEngineServer>(async op =>
        //{
        //    op.RegirstFlowType(0, "测试流程");

        //    op.FlowBuilder(flowBuilder);

        //    op.RegisterFlowUnitExcutionMode<mode>();

        //});



        services.AddSingleton<IProblemDetailsWriter, VampirewalMiniApiResultProblemDetailsWriter>();//这个不是很好用，但是还是保留


        services.AddSingleton<IVampirewalMiniApiResultProvider, testProvider>();

        services.AddEndpointsApiExplorer();

        services.AddSwaggerGen(c =>
        {
            //c.DocInclusionPredicate((docName, apiDescription) =>
            //{

            //});

            c.SwaggerDoc("v1", new OpenApiInfo
            {
                Title = "测试MiniApi-V1",
                Version = "v1",
                Description = "haha"
            }
            );
            //设置xml引用
            var filePath = Path.Combine(System.AppContext.BaseDirectory, "test.ViewModel.xml");
            c.IncludeXmlComments(filePath);

            //添加授权
            var schemeName = "Bearer";
            c.AddSecurityDefinition(schemeName, new OpenApiSecurityScheme
            {
                In = ParameterLocation.Header,
                Description = "请输入不带有Bearer的Token",
                Name = "Authorization",
                Type = SecuritySchemeType.Http,
                Scheme = schemeName.ToLowerInvariant(),
                BearerFormat = "JWT"
            });
            c.AddSecurityRequirement(new OpenApiSecurityRequirement {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id = schemeName,

                            }
                        },
                        new string[0]
                    }
                });
        });

        #region 这个是响应静态页面用的
        var service = new HttpDmtpService();
        var config = new TouchSocketConfig()//配置
               .SetListenIPHosts(new IPHost[] { new IPHost(7799) })
               .ConfigureContainer(a =>
               {
                   a.AddConsoleLogger();
               })
               .ConfigurePlugins(a =>
               {
                   a.UseHttpStaticPage().AddFolder($"{AppDomain.CurrentDomain.BaseDirectory}dist");

                   a.UseDefaultHttpServicePlugin();
               });

        service.Setup(config);

        service.Start();

        try
        {
            Enterprise.ForTest();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        #endregion


        services.AddVampirewalCoreScheduledTask(config =>
        {
            config.Register<TestTask>(option =>
            {
                option.JobName = "测试1";
                option.JobDescription = "每10秒执行1次";
                option.CronExpression = "*/10 * * * * *";
                option.RetryCount = 3;
            });

            //config.Register<TestTask>(option =>
            //{
            //    option.JobName = "测试2";
            //    option.JobDescription = "每15秒执行1次";
            //    option.CronExpression = "*/15 * * * * *";
            //});

        });
    }

    private void flowBuilder(IVampirewalFlowBuilder bu)
    {
        bu.Builder("ceshi001", "测试", 0, (nodes, param) =>
        {
            nodes.SetStartNode(ExcutionModeType.EveryOne).SetNormalNode(1, "aa", "asd", ExcutionModeType.EveryOne, link =>
            {
                link.SetPreviousUnitIndex(0).SetCondition("");
            });

        });


    }

    public override void OnAppRun(bool IsRun)
    {
        //base.OnAppRun(IsRun);
    }

    public override void OnAppExit(bool IsRun)
    {
        //base.OnAppExit(IsRun);
    }

    public override void GlobalException(string source, Exception exception)
    {
        var dialog= Services.GetService<IVampirewalCoreDialogMessage>();

        dialog.ShowPopupWindow(new Vampirewal.Core.WindoSetting.PopupWindowSetting()
        {
            Message = $"{source};{exception.Message}",
            OwnerWindow=WindowsManager.GetInstance().MainWindow,
            Type= Vampirewal.Core.WindoSetting.MessageType.Error
        });
    }
}

public class TestWebApiBootStartup : VampirewalWebApiBootStartup
{
    protected override string FirstViewKey => "MainView";

    protected override void RegisterService(IServiceCollection services)
    {
        //services.AddVampirewalCoreConfig($"{AppDomain.CurrentDomain.BaseDirectory}AppConfig.json", options =>
        //{
        //    options.RegisterOptions<DbBaseOptions>();
        //});

        services.AddVampirewalCoreAppConfig(config =>
        {
            config.LoadOption<DbBaseOptions>();
        });

        services.AddSingleton<IVampirewalCoreDataContext, DataContext>();
        //services.UseVampirewalCoreSqlSugar(new testdc());
        services.UseVampirewalCoreSqlSugar<testdc>();
        services.AddTransient(typeof(SqlSugarRepository<>));
        services.AddSingleton<IVampirewalCoreLogService, VampirewalCoreLogService>();
        services.AddVampirewalCoreDialogMessage();
        services.AddSingleton<IVampirewalOperationExcelService, VampirewalOperationExcelService>();
        services.AddSingleton<IVampirewalCoreComputerService, VampirewalCoreComputerService>();
        services.AddSingleton<IVampirewalCoreActionService, VampirewalCoreActionService>();
        services.AddSingleton<IVampirewalCoreValidationService, VampirewalCoreValidationService>();
        services.AddVampirewalCoreEventBusFactory();

        services.UseVampirewalWebApi(config =>
        {
            config.SetIpPort("*", 9999);

            config.AddVampirewalMiddleware<GlobalExceptionMiddleware>();
            config.AddVampirewalMiddleware<TestMiddleware>();

            config.UseWebApiDoc(new VampirewalApiDocOptions()
            {
                LocalPath = $"{AppDomain.CurrentDomain.BaseDirectory}dist",
                Title = "测试",
                Version = "1.0.0.1"
            });
        });
    }
}


public class TestBootStartupOld : VampirewalBootStartUp
{
    protected override string FirstViewKey { get; }

    public override void OnAppExit(bool IsRun)
    {
        //当程序退出时触发
    }

    public override void OnAppRun(bool IsRun)
    {
        //当程序启动时触发
    }

    protected override void RegisterService(IServiceCollection services)
    {

    }
}

public class TestModuleBootStartUp : IVampirewalModuleBootStartup
{
    public string ModuleName => "测试模块";

    public void BuildModuleBootStartUp(IServiceCollection services)
    {

    }

    public void LoadModuleOption(IVampirewalCoreAppConfig config)
    {
        config.LoadOption<TestModuleOptions>();
    }

    public void OnModuleRun(IServiceProvider service)
    {

    }
}

public class TestModuleOptions:IOptionsHotReloadInit<TestModuleOptions>
{
    public string Name { get; set; }

    public List<TestModel> Models { get; set; }

    /// <summary>
    /// 数据库类型
    /// </summary>
    public DBTypeEnum? DbType { get; set; } = DBTypeEnum.Sqlite;

    public void HotReload(TestModuleOptions config)
    {

    }

    public void Init(TestModuleOptions config)
    {
        config.Name = "haha";
    }
}


public class mode : IVampirewalFlowUnitExcutionMode
{
    public List<Tuple<string, string>> DepartmentHead(WorkParamCollection Param)
    {
        throw new NotImplementedException();
    }

    public List<Tuple<string, string>> EveryOne(WorkParamCollection Param)
    {
        throw new NotImplementedException();
    }

    public List<Tuple<string, string>> Role(WorkParamCollection Param)
    {
        throw new NotImplementedException();
    }
}

public class TestRule : IVampirewalRule<TestModel>
{

    public void Build(IVampirewalRuleBuilder<TestModel> data)
    {
        data.StartWith<TestSetp>().IfElse<TestIfElseSetp, TestIfElseSetp>(w => w.Name == "傻屌");
    }
}

public class TestSetp : IVampirewalRuleSetp<TestModel>
{

    public VampirewalRuleExcuteResult Run(IVampirewalRuleSetpContext<TestModel> context)
    {
        return VampirewalRuleExcuteResult.Next();
    }
}

public class TestIfSetp : IVampirewalRuleSetp<TestModel>
{
    public VampirewalRuleExcuteResult Run(IVampirewalRuleSetpContext<TestModel> context)
    {
        context.NextNeedData = new List<string>()
        {
            "haha","shadiao"
        };

        return VampirewalRuleExcuteResult.Next();
    }
}


public class TestIfElseSetp : IVampirewalRuleSetp<TestModel>
{
    public VampirewalRuleExcuteResult Run(IVampirewalRuleSetpContext<TestModel> context)
    {
        context.Builder.IF<TestIfSetp>(w => w.Name == "傻屌");



        return VampirewalRuleExcuteResult.Next();
    }

}

public class testdc : VampirewalCoreSqlSugarSetup
{
    public override void CodeFirst()
    {
        CreateTable<TestModel>();
        CreateTable<TestBillModel>();
        CreateTable<TestDetailModel>();
        CreateTable<TestDetailModel2>();
        CreateTable<Logger>();
    }

    public override void InitData()
    {
        if (Client.Queryable<TestModel>().Any())
        {
        }
        else
        {
        }
    }

    public override Type[] FilterSugarTableType(Type[] types)
    {
        List<string> list = new List<string>()
        {
            "Flow","FlowLink"
        };

        types = types.Where(w => !list.Contains(w.Name)).ToArray();

        return base.FilterSugarTableType(types);
    }
}

[SugarTable("TestModel")]
public class TestModel : TopModel
{
    public string? Name { get; set; }
}



public class TestTask : IJob
{
    public Task ExcuteAsync(JobContext context)
    {
        StringBuilder sb = new StringBuilder();

        sb.AppendLine("------");

        sb.AppendLine($"任务名称：{context.JobName}");
        sb.AppendLine($"任务描述：{context.JobDescription}");
        sb.AppendLine($"任务已执行次数：{context.ExcuteCount}");

        sb.AppendLine("------");
        sb.AppendLine();

        Trace.WriteLine(sb.ToString());

        //var application= VampirewalCoreContext.GetInstance().GetService<IApplicationService>();
        //var dialog= VampirewalCoreContext.GetInstance().GetService<IVampirewalCoreDialogMessage>();

        //application.BeginInvoke(() =>
        //{
        //    dialog.ShowPopupWindow(new Vampirewal.Core.WindoSetting.PopupWindowSetting()
        //    {
        //        Message = sb.ToString(),
        //        OwnerWindow = WindowsManager.GetInstance().MainWindow,
        //        Type = Vampirewal.Core.WindoSetting.MessageType.Successful
        //    });
        //});

        

        return Task.CompletedTask;
    }

    public async Task OnExcuteErrorAsync(JobContext context, Exception ex)
    {
        await Task.CompletedTask;
    }
}